package com.hdl.dao.impl;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdl.dao.MallTypeDao;
import com.hdl.entity.MallType;
import com.hdl.util.Druidutils;
import com.hdl.util.JedisUtils;

import redis.clients.jedis.Jedis;

public class MallTypeDaoImpl implements MallTypeDao{

	private JdbcTemplate template = new JdbcTemplate(Druidutils.getDataSource());
	
	@Override
	public List<MallType> findAll() {
		
		//定义sql
		String sql = "select * from mall_type";
		return template.query(sql, new BeanPropertyRowMapper<MallType>(MallType.class));
	}

	@Override
	public String findAllJson() {
		//获取redis客户端连接对象
		Jedis jedis = JedisUtils.getJedis();
		//从redis中获取数据
		String type = jedis.get("type");
		//判断缓存中是否有数据
		if(type == null || type.length() == 0) {//没有
			System.out.println("第一次，没有缓存");
			//从数据库中拿数据
			List<MallType> list = findAll();
			//将对象转换为json字符串
			ObjectMapper mapper = new ObjectMapper();
			try {
				type = mapper.writeValueAsString(list);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			//存入redis中
			jedis.set("type",type);
			
			//归还连接
			jedis.close();
		}
		System.out.println("有缓存");
		return type;
	}

}
